<template>
  <div class="users">
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/index' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索框 -->
    <el-input v-model="query" class="input-with-select" placeholder="请输入内容">
      <el-button slot="append" @click="searchUser" icon="el-icon-search"></el-button>
    </el-input>
    <!-- 添加用户按钮 -->
    <el-button class="addBtn" type="success" @click="changeDialog">添加用户</el-button>
    <!-- 添加对话框 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="30%">
      <el-form ref="form" :rules="rules" :model="form" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input placeholder="请输入用户名" v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" placeholder="请输入密码" v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input placeholder="请输入邮箱" v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input placeholder="请输入手机号" v-model="form.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="changeDialog">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改对话框 -->
    <el-dialog title="修改用户" :visible.sync="editVisible" width="30%">
      <el-form ref="editForm" :rules="rules" :model="editForm" label-width="80px">
        <el-form-item label="用户名">
          <el-tag type="info">{{ editForm.username }}</el-tag>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input placeholder="请输入邮箱" v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input placeholder="请输入手机号" v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible=false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 表格 -->
    <el-table :data="list" style="width: 100%" border stripe align="center">
      <el-table-column prop="username" label="用户名" width="180"></el-table-column>
      <el-table-column prop="mobile" label="电话" width="180"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column label="用户状态">
        <!-- obj.row 可以拿到整个遍历的对象 -->
        <template v-slot:default="obj">
          <el-switch
            v-model="obj.row.mg_state"
            @change="changeStatus(obj.row)"
            active-color="#13ce66"
            inactive-color="#ff4949"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template v-slot:default="obj">
          <!-- {{ obj.row.id }} -->
          <el-button
            plain
            size="small"
            type="primary"
            icon="el-icon-edit"
            @click="changeEdit(obj.row)"
          ></el-button>
          <el-button
            plain
            size="small"
            type="danger"
            icon="el-icon-delete"
            @click="delUser(obj.row.id)"
          ></el-button>
          <el-button
            plain
            size="small"
            type="success"
            icon="el-icon-check"
            @click="showAssignVisible(obj.row)"
          >分配角色</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="assignVisible" width="30%">
      <el-form ref="assignForm" :model="assignForm" label-width="80px">
        <el-form-item label="用户名">
          <el-tag type="info">{{ assignForm.username }}</el-tag>
        </el-form-item>
        <el-form-item label="角色列表">
          <el-select v-model="assignForm.rid" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="assignVisible=false">取 消</el-button>
        <el-button type="primary" @click="assRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分页器 -->
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagenum"
        :page-sizes="[3, 4, 5, 6]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      pagenum: 1,
      pagesize: 5,
      total: 1,
      list: [],
      query: '',
      dialogVisible: false,
      editVisible: false,
      assignVisible: false,
      form: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editForm: {
        username: '222',
        mobile: '',
        email: '',
        id: ''
      },
      assignForm: {
        username: '',
        id: '',
        rid: ''
      },
      options: [],
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 12,
            message: '用户名长度在 3 到 12 个字符',
            trigger: ['blur', 'change']
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 3,
            max: 12,
            message: '密码长度在 3 到 12 个字符',
            trigger: ['blur', 'change']
          }
        ],
        email: [
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change']
          }
        ],
        mobile: [
          {
            pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
            message: '请输入正确的手机号',
            trigger: ['blur', 'change']
          }
        ]
      }
    }
  },
  methods: {
    // 获取列表信息
    async getUserList () {
      try {
        // 发送 get 获取用户的 this.$axios
        const { data } = await this.$axios.get('users', {
          // 配置 params
          params: {
            query: this.query,
            pagenum: this.pagenum,
            pagesize: this.pagesize
          }
        })
        this.list = data.users
        this.total = data.total
        this.pagenum = data.pagenum
      } catch (e) {
        console.log(e)
      }
    },
    handleSizeChange (val) {
      this.pagesize = val
      this.pagenum = 1
      this.getUserList()
    },
    handleCurrentChange (val) {
      this.pagenum = val
      this.getUserList()
    },
    // 删除功能
    async delUser (id) {
      try {
        await this.$confirm('亲,确定要删除当前用户吗', '温馨提示', {
          type: 'warning'
        })
        const { meta } = await this.$axios.delete(`users/${id}`)
        if (meta.status === 200) {
          this.$message.success('删除成功')
          if (this.list.length === 1 && this.pagenum > 1) {
            this.pagenum--
          }
          this.getUserList()
        } else {
          this.$message.error('删除失败')
        }
      } catch (e) {
        console.log(e)
      }
    },
    // 根据搜索关键字, 搜索数据展示
    searchUser () {
      // 搜索后, 需要将当前页改为第一页
      this.pagenum = 1
      this.getUserList()
    },
    // 修改状态功能
    async changeStatus (row) {
      try {
        const { meta } = this.$axios.put(
          `users/${row.id}/state/${row.mg_state}`
        )
        if (meta.status === 200) {
          this.$message.success('修改成功')
          this.getUserList()
        } else {
          this.$message.error(meta.message)
        }
      } catch (e) {
        console.log(e)
      }
    },
    // 弹出对话框
    changeDialog () {
      this.dialogVisible = !this.dialogVisible
    },
    // 确认添加用户
    async addUser () {
      try {
        const { meta } = await this.$axios.post('users', this.form)
        if (meta.status === 201) {
          this.$message.success(meta.msg)
          this.changeDialog()
          this.total++
          // 重新渲染最后一页
          this.pagenum = Math.ceil(this.total / this.pagesize)
          this.getUserList()
          this.$refs.form.resetFields()
        } else {
          this.$message.error(meta.msg)
        }
      } catch (e) {
        console.log(e)
      }
    },
    // 修改用户
    // 弹出对话框
    changeEdit (row) {
      this.editVisible = true
      this.editForm.username = row.username
      this.editForm.email = row.email
      this.editForm.mobile = row.mobile
      this.editForm.id = row.id
    },
    // 确认修改
    async editUser () {
      try {
        await this.$refs.editForm.validate()
        // 校验成功
        const { id, email, mobile } = this.editForm
        const { meta } = await this.$axios.put(`users/${id}`, {
          email,
          mobile
        })
        if (meta.status === 200) {
          this.$message.success(meta.msg)
          // 关闭模态框
          this.editVisible = false
          // 重新渲染
          this.getUserList()
        } else {
          this.$message.error(meta.msg)
        }
      } catch (e) {
        console.log(e)
      }
    },
    // 弹出分配对话框
    async showAssignVisible (row) {
      try {
        this.assignVisible = true
        this.assignForm.username = row.username
        this.assignForm.id = row.id
        const { data, meta } = await this.$axios.get(`users/${row.id}`)
        if (meta.status === 200) {
          this.assignForm.rid = data.rid === -1 ? '' : data.rid
        }
        const res = await this.$axios.get('roles')
        this.options = res.data
      } catch (e) {
        console.log(e)
      }
    },
    // 分配角色
    async assRoles () {
      try {
        const { id, rid } = this.assignForm
        const { meta } = await this.$axios.put(`users/${id}/role`, { rid })
        if (meta.status === 200) {
          this.assignVisible = false
        }
      } catch (e) {
        console.log(e)
      }
    }
  },
  created () {
    this.getUserList()
  }
}
</script>

<style lang = 'scss' scoped>
.el-table {
  margin-top: 20px;
}
.block {
  margin-top: 20px;
}
.el-breadcrumb {
  height: 40px;
  line-height: 40px;
  border-bottom: 1px solid #ccc;
  margin-bottom: 10px;
}
.input-with-select {
  width: 300px;
  margin-bottom: 10px;
}
.addBtn {
  margin: 0 20px;
}
</style>
